ext.define('ext', function() {

var display = extension.display;
var filters = extension.filters;
var messages = extension.messages;
var mutations = extension.mutations;
var placeholders = extension.placeholders;
var preferences = extension.preferences;
var documentURL;
var ids = [];

function sendMessage(type, data) {
    messages.runtime.send({type: type, info: data}, function(message) {
        if (message)
            API(message['status'], message);
    });
}

function receiveMessage(message) {
    switch (message.type) {
        case 'inspect':
            sendMessage('audit', {
                indexed: true,
                plugin: filters.info()
            });
            break;
        case 'filter':
            filters.update(message.info);
            mutations.scan();
            break;
    }
}

function run() {
    documentURL = document.URL;
    mutations.observe();
    sendMessage('status');
}

function audit(metadata) {
    if (documentURL == document.URL) {
        var info = {
            indexed: ids.indexOf(metadata.id) !== -1,
            plugin: filters.info(metadata)
        };
        if (!info.indexed)
            ids.push(metadata.id);
        sendMessage('audit', info);
    }
}

function API(var_args) {
    switch (arguments[0]) {
        case 'capture':
            preferences.set(arguments[1]);
            filters.capture(arguments[1]);
            mutations.scan();
            break;
        case 'allow':
            preferences.set(arguments[1]);
            filters.allow();
            mutations.scan();
            break;
        case 'deny':
            filters.deny();
            mutations.scan();
            break;
        case 'destroy':
            filters.allow();
            mutations.scan();
            break;
        case 'block':
            filters.block(arguments[1]);
            mutations.scan();
            break;
        case 'validate':
            if (documentURL != document.URL) {
                documentURL = document.URL;
                sendMessage('update');
            }
            break;
    }
}

return {
    initialize: function() {
        if (window.FlashControl == null) {
            window.FlashControl = API;
            chrome.runtime.onMessage.addListener(receiveMessage);
            mutations.bind();
            display.bind();
            filters.bind();
            placeholders.bind();
            messages.listen({
                'document-replaced': run,
                'insert': audit
            });
            run();
        }
    }
};

});

ext.initialize();
